<template>
  <div class="exam-page">

    <!-- 悬浮进度球 -->
    <div class="floating-progress" :style="{ transform: 'translate(-50%, -50%) scale(' + (1 + (currentQuestion + 1) / totalQuestions * 0.1) + ')' }">
      <div class="progress-circle">
        <svg width="80" height="80" viewBox="0 0 80 80">
          <!-- 背景圆 -->
          <circle cx="40" cy="40" r="35" fill="none" stroke="#f0f0f0" stroke-width="6"/>
          <!-- 进度圆 -->
          <circle cx="40" cy="40" r="35" fill="none" stroke="#4CAF50" stroke-width="6" 
                  :stroke-dasharray="2 * Math.PI * 35" 
                  :stroke-dashoffset="2 * Math.PI * 35 * (1 - (currentQuestion + 1) / totalQuestions)"
                  stroke-linecap="round" :transform="'rotate(-90 40 40)'"/>
        </svg>
        <div class="progress-number">{{ currentQuestion + 1 }}</div>
      </div>
      <div class="progress-text">第 {{ currentQuestion + 1 }} 个汉字</div>
    </div>

    <!-- 考试内容区域 -->
    <div class="exam-content">
      <!-- 当前题目 -->
      <div class="current-question">
        <h3>请书写汉字: <span class="target-hanzi">{{ currentQuestionData.hanzi }}</span></h3>
      </div>

      <!-- 汉字书写区域 -->
      <div class="writing-area">
        <canvas 
          id="hanzi-canvas" 
          ref="hanziCanvas" 
          width="400" 
          height="400"
          class="hanzi-canvas"
          @mousedown="startDrawing"
          @mousemove="draw"
          @mouseup="stopDrawing"
          @mouseleave="stopDrawing"
          @touchstart="startDrawing"
          @touchmove="draw"
          @touchend="stopDrawing"
        ></canvas>
      </div>

      <!-- 考试控制按钮 -->
      <div class="exam-controls">
        <button @click="clearCanvas" class="btn btn-secondary">
            🧹 清除
        </button>
        <button @click="submitAnswer" class="btn btn-primary">
          ✅ 提交答案
        </button>
        <button @click="generateCollection" class="btn btn-warning">
            📚 生成合集
        </button>
      </div>

      <!-- Toast弹窗 -->
      <div v-if="showToast" class="toast-container">
        <div :class="['toast', 'toast-' + toastType]">
          <div class="toast-icon">
            <span v-if="toastType === 'success'">✅</span>
            <span v-else-if="toastType === 'error'">❌</span>
            <span v-else>⚠️</span>
          </div>
          <div class="toast-content">
            <div class="toast-message">{{ toastMessage }}</div>
          </div>
          <button class="toast-close" @click="showToast = false">×</button>
        </div>
      </div>

      <!-- 合集弹窗 -->
      <div v-if="showCollectionModal" class="modal-overlay" @click="showCollectionModal = false">
        <div class="modal-content" @click.stop>
          <div class="modal-header">
            <h3>汉字书写合集</h3>
            <button @click="showCollectionModal = false" class="modal-close">×</button>
          </div>
          <div class="modal-body">
            <img :src="collectionImageData" alt="汉字书写合集" class="collection-image" />
          </div>
          <div class="modal-footer">
            <button @click="downloadCollection" class="btn btn-primary">下载合集</button>
            <button @click="showCollectionModal = false" class="btn btn-secondary">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, nextTick } from "vue";
import HanziWriter from "hanzi-writer";

import { resolveResource } from '@tauri-apps/api/path';
import { readTextFile } from '@tauri-apps/plugin-fs';

// 考试配置
const totalQuestions = 10;

// 考试状态
const examQuestions = ref<Array<{hanzi: string, pinyin: string}>>([]);
const currentQuestion = ref(0);
const score = ref(0);
const examFinished = ref(false);
const answerSubmitted = ref(false);

// toast弹窗相关变量
const showToast = ref(false);
const toastMessage = ref('');
const toastType = ref('success'); // success, error, warning

// 考试结果记录
const examResults = ref<Array<{hanzi: string, correct: boolean}>>([]);

// 响应式变量
const hanziCanvas = ref<HTMLCanvasElement | null>(null);
const isDrawing = ref(false);
const lastX = ref(0);
const lastY = ref(0);
const savedImages = ref<string[]>([]);
const showCollectionModal = ref(false);
const collectionImageData = ref(''); // 保存的图片数据URL

// 汉字书写器实例
let writer: HanziWriter | null = null;

// 当前题目数据
const currentQuestionData = computed(() => {
  return examQuestions.value[currentQuestion.value] || { hanzi: '', pinyin: '' };
});

// 加载汉字数据
const loadHanziData = async () => {
  try {
    const resourcePath = await resolveResource('data/primary_school_chinese.csv');
    const csvText = await readTextFile(resourcePath);
    
    const lines = csvText.split('\n').slice(1); // 跳过标题行
    const allHanzi: Array<{hanzi: string, pinyin: string}> = [];
    
    for (const line of lines) {
      if (line.trim()) {
        const [, hanzi, pinyin] = line.split(',');
        if (hanzi && pinyin) {
          allHanzi.push({
            hanzi: hanzi.trim(),
            pinyin: pinyin.trim()
          });
        }
      }
    }
    
    // 随机选择10个不重复的汉字
    const shuffled = allHanzi.sort(() => 0.5 - Math.random());
    examQuestions.value = shuffled.slice(0, totalQuestions);
    
  } catch (error) {
    console.error('加载汉字数据失败:', error);
    // 使用默认汉字数据
    examQuestions.value = [
      { hanzi: '人', pinyin: 'rén' },
      { hanzi: '口', pinyin: 'kǒu' },
      { hanzi: '日', pinyin: 'rì' },
      { hanzi: '月', pinyin: 'yuè' },
      { hanzi: '水', pinyin: 'shuǐ' },
      { hanzi: '火', pinyin: 'huǒ' },
      { hanzi: '山', pinyin: 'shān' },
      { hanzi: '木', pinyin: 'mù' },
      { hanzi: '田', pinyin: 'tián' },
      { hanzi: '土', pinyin: 'tǔ' }
    ];
  }
};

// 初始化考试
const initExam = async () => {
  await loadHanziData();
  currentQuestion.value = 0;
  score.value = 0;
  examFinished.value = false;
  answerSubmitted.value = false;
  examResults.value = [];
  
  if (examQuestions.value.length > 0) {
    setupWriter();
  }
};

// 设置Canvas书写器
const setupWriter = () => {
  // 初始化Canvas
  nextTick(() => {
    if (hanziCanvas.value) {
      drawRiceGrid(); // 绘制米字格背景
    }
  });
};

// 提交答案
const submitAnswer = () => {
  // 对于Canvas书写，我们总是认为用户完成了书写
  const isCorrect = true;
  
  // 记录结果
  saveCurrentImage();
  examResults.value.push({
    hanzi: currentQuestionData.value.hanzi,
    correct: isCorrect
  });
  
  // 更新分数并显示toast消息
  if (isCorrect) {
    score.value++;
    showToastMessage('✅ 正确！书写准确！', 'success');
  } else {
    showToastMessage('❌ 不正确，请重新书写', 'error');
  }
  
  // 延迟后进入下一题
  setTimeout(() => {
    if (currentQuestion.value < totalQuestions - 1) {
      currentQuestion.value++;
      setupWriter();
    } else {
      examFinished.value = true;
      // 第十个汉字时自动弹出合集
      generateCollection();
    }
  }, 1500);
};



// Canvas绘制相关函数
const drawRiceGrid = () => {
  if (!hanziCanvas.value) return;
  
  const canvas = hanziCanvas.value;
  const ctx = canvas.getContext('2d');
  if (!ctx) return;
  
  const width = canvas.width;
  const height = canvas.height;
  const gridSize = 40; // 网格大小
  
  // 清空画布
  ctx.clearRect(0, 0, width, height);
  
  // 绘制背景
  ctx.fillStyle = '#f9f9f9';
  ctx.fillRect(0, 0, width, height);
  
  // 绘制网格线
  ctx.strokeStyle = '#e0e0e0';
  ctx.lineWidth = 1;
  
  // 垂直网格线
  for (let x = 0; x <= width; x += gridSize) {
    ctx.beginPath();
    ctx.moveTo(x, 0);
    ctx.lineTo(x, height);
    ctx.stroke();
  }
  
  // 水平网格线
  for (let y = 0; y <= height; y += gridSize) {
    ctx.beginPath();
    ctx.moveTo(0, y);
    ctx.lineTo(width, y);
    ctx.stroke();
  }
  
  // 绘制米字格对角线
  ctx.strokeStyle = '#b0b0b0';
  ctx.lineWidth = 1;
  
  // 主对角线
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(width, height);
  ctx.stroke();
  
  ctx.beginPath();
  ctx.moveTo(width, 0);
  ctx.lineTo(0, height);
  ctx.stroke();
  
  // 中心十字线
  ctx.strokeStyle = '#909090';
  ctx.beginPath();
  ctx.moveTo(width / 2, 0);
  ctx.lineTo(width / 2, height);
  ctx.stroke();
  
  ctx.beginPath();
  ctx.moveTo(0, height / 2);
  ctx.lineTo(width, height / 2);
  ctx.stroke();
};

// 开始绘制
const startDrawing = (e: MouseEvent | TouchEvent) => {
  isDrawing.value = true;
  const canvas = hanziCanvas.value;
  if (!canvas) return;
  
  const rect = canvas.getBoundingClientRect();
  let clientX, clientY;
  
  if (e instanceof MouseEvent) {
    clientX = e.clientX;
    clientY = e.clientY;
  } else {
    const touch = e.touches[0];
    clientX = touch.clientX;
    clientY = touch.clientY;
  }
  
  lastX.value = clientX - rect.left;
  lastY.value = clientY - rect.top;
};

// 绘制
const draw = (e: MouseEvent | TouchEvent) => {
  if (!isDrawing.value) return;
  
  const canvas = hanziCanvas.value;
  const ctx = canvas?.getContext('2d');
  if (!canvas || !ctx) return;
  
  const rect = canvas.getBoundingClientRect();
  let clientX, clientY;
  
  if (e instanceof MouseEvent) {
    clientX = e.clientX;
    clientY = e.clientY;
  } else {
    const touch = e.touches[0];
    clientX = touch.clientX;
    clientY = touch.clientY;
  }
  
  const currentX = clientX - rect.left;
  const currentY = clientY - rect.top;
  
  // 设置画笔样式
  ctx.strokeStyle = '#000000';
  ctx.lineWidth = 3;
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';
  
  // 绘制线条
  ctx.beginPath();
  ctx.moveTo(lastX.value, lastY.value);
  ctx.lineTo(currentX, currentY);
  ctx.stroke();
  
  lastX.value = currentX;
  lastY.value = currentY;
};

// 停止绘制
const stopDrawing = () => {
  isDrawing.value = false;
};

// 清除画布
const clearCanvas = () => {
  const canvas = hanziCanvas.value;
  const ctx = canvas?.getContext('2d');
  if (!canvas || !ctx) return;
  
  drawRiceGrid(); // 重新绘制米字格
};

// 保存当前图片
const saveCurrentImage = () => {
  const canvas = hanziCanvas.value;
  if (!canvas) return;
  
  const imageData = canvas.toDataURL('image/png');
  console.info('保存的图片数据:', imageData);
  savedImages.value.push(imageData);
  showToastMessage('✅ 图片已保存！', 'success');
};

// 生成合集
const generateCollection = () => {
  if (savedImages.value.length === 0) {
    showToastMessage('❌ 没有保存的图片！', 'error');
    return;
  }
  
  // 创建合集画布
  const collectionCanvas = document.createElement('canvas');
  const ctx = collectionCanvas.getContext('2d');
  if (!ctx) return;
  
  // 计算合集画布大小（动态网格布局）
  const imagesPerRow = Math.min(3, savedImages.value.length); // 最多3列，但图片少时减少列数
  const imagesPerCol = Math.ceil(savedImages.value.length / imagesPerRow);
  const imgWidth = 120; // 进一步缩减图片宽度为110像素
  const imgHeight = 120;
  const canvasWidth = imgWidth * imagesPerRow; // 减少间距
  const canvasHeight = imgHeight * imagesPerCol;
  
  collectionCanvas.width = canvasWidth;
  collectionCanvas.height = canvasHeight;
  
  // 绘制白色背景
  ctx.fillStyle = '#ffffff';
  ctx.fillRect(0, 0, collectionCanvas.width, collectionCanvas.height);
  
  // 绘制所有图片
  savedImages.value.forEach((imageData, index) => {
    const img = new Image();
    img.onload = () => {
      const row = Math.floor(index / imagesPerRow);
      const col = index % imagesPerRow;
      const x = col * imgWidth;
      const y = row * imgHeight;
      
      // 绘制图片
      ctx.drawImage(img, x, y, imgWidth, imgHeight);
      
      // 绘制边框
      ctx.strokeStyle = '#cccccc';
      ctx.lineWidth = 1;
      ctx.strokeRect(x, y, imgWidth, imgHeight);
      
      // 如果是最后一张图片，生成合集数据并显示弹窗
      if (index === savedImages.value.length - 1) {
        const collectionData = collectionCanvas.toDataURL('image/png');
        // 保存合集数据用于弹窗展示
        collectionImageData.value = collectionData;
        // 显示合集弹窗
        showCollectionModal.value = true;
      }
    };
    img.src = imageData;
  });
  
  showToastMessage('📚 合集生成中...', 'success');
};

// 下载合集
const downloadCollection = () => {
  if (collectionImageData.value) {
    const link = document.createElement('a');
    link.download = '汉字书写合集.png';
    link.href = collectionImageData.value;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    showToastMessage('📥 合集下载成功！', 'success');
  }
};



// 显示toast消息
const showToastMessage = (message: string, type: string = 'success') => {
  toastMessage.value = message;
  toastType.value = type;
  showToast.value = true;
  
  // 3秒后自动隐藏
  setTimeout(() => {
    showToast.value = false;
  }, 3000);
};

// 生命周期
onMounted(() => {
  initExam();
});

onUnmounted(() => {
  if (writer) {
    writer.cancelQuiz();
    writer.hideCharacter();
    writer = null;
  }
});
</script>

<style scoped>
.exam-page {
  max-width: 800px;
  margin: 0 auto;
  min-height: calc(100vh - 140px);
}

.exam-header {
  text-align: center;
  margin-bottom: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.exam-header h2 {
  margin: 0 0 15px 0;
  font-size: 2.2rem;
}

.exam-info {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.1rem;
}

/* 悬浮进度球样式 */
.floating-progress {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.progress-circle {
  position: relative;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 50%;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  border: 2px solid #f0f0f0;
}

.progress-number {
  position: absolute;
  font-size: 1.8rem;
  font-weight: 700;
  color: #333;
}

.floating-progress .progress-text {
  font-size: 0.9rem;
  font-weight: 600;
  color: #666;
  background: white;
  padding: 4px 12px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  white-space: nowrap;
}

/* 悬浮球悬停效果 */
.floating-progress:hover {
  transform: translate(-50%, -50%) scale(1.1) !important;
}

.floating-progress:hover .progress-circle {
  box-shadow: 0 12px 35px rgba(0, 0, 0, 0.2);
}

.floating-progress:hover .progress-text {
  background: #4CAF50;
  color: white;
}



.exam-content {
  background: white;
  padding: 10px;
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.current-question {
  text-align: center;
  margin-bottom: 30px;
}

.target-hanzi {
  font-size: 3rem;
  color: #333;
  font-weight: bold;
}

.pinyin {
  font-size: 1.2rem;
  color: #666;
  margin-top: 10px;
}

.writing-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  margin: 20px 0;
}

.hanzi-canvas {
  border: 2px solid #ddd;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  background: #f9f9f9;
  cursor: crosshair;
}

.canvas-controls {
  display: flex;
  gap: 10px;
  justify-content: center;
  flex-wrap: wrap;
}

.writer-target {
  border: 2px solid #e0e0e0;
  border-radius: 10px;
  background: #f9f9f9;
}

.exam-controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 25px;
  font-size: 1rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(76, 175, 80, 0.3);
}

.btn-primary:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.btn-secondary {
  background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%);
  color: white;
}

.btn-secondary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(33, 150, 243, 0.3);
}

.btn-warning {
  background: linear-gradient(135deg, #FF9800 0%, #F57C00 100%);
  color: white;
}

.btn-warning:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(255, 152, 0, 0.3);
}



.exam-result {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.result-card {
  background: white;
  padding: 40px;
  border-radius: 20px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 500px;
  width: 100%;
}

.result-card h3 {
  color: #333;
  margin-bottom: 30px;
  font-size: 2rem;
}

.score-summary {
  margin-bottom: 30px;
}

.final-score {
  font-size: 1.5rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.percentage {
  font-size: 1.2rem;
  color: #666;
  margin-bottom: 15px;
}

.grade {
  font-size: 1.3rem;
  font-weight: bold;
  padding: 10px 20px;
  border-radius: 25px;
  display: inline-block;
}

.grade.excellent {
  background: #e8f5e8;
  color: #2e7d32;
}

.grade.good {
  background: #e3f2fd;
  color: #1565c0;
}

.grade.pass {
  background: #fff3e0;
  color: #ef6c00;
}

.grade.fail {
  background: #ffebee;
  color: #c62828;
}

.result-details {
  margin: 30px 0;
}

.result-details h4 {
  margin-bottom: 15px;
  color: #333;
}

.result-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.result-item:last-child {
  border-bottom: none;
}

.hanzi {
  font-size: 1.2rem;
  font-weight: bold;
}

.status.correct {
  color: #4caf50;
}

.status.incorrect {
  color: #f44336;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .exam-page {
    padding: 10px;
  }
  
  .exam-header {
    padding: 15px;
  }
  
  .exam-header h2 {
    font-size: 1.8rem;
  }
  
  .exam-info {
    flex-direction: column;
    gap: 10px;
  }
}

/* Toast弹窗样式 */
.toast-container {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
  max-width: 350px;
}

.toast {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  animation: slideInRight 0.3s ease-out;
  margin-bottom: 10px;
}

.toast-success {
  background: #e8f5e8;
  border-left: 4px solid #4caf50;
  color: #2e7d32;
}

.toast-error {
  background: #ffebee;
  border-left: 4px solid #f44336;
  color: #c62828;
}

.toast-warning {
  background: #fff3e0;
  border-left: 4px solid #ff9800;
  color: #ef6c00;
}

.toast-icon {
  font-size: 1.5rem;
  margin-right: 15px;
}

.toast-content {
  flex: 1;
}

.toast-message {
  font-weight: bold;
  font-size: 1rem;
}

.toast-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: inherit;
  opacity: 0.7;
  margin-left: 15px;
}

.toast-close:hover {
  opacity: 1;
}

@keyframes slideInRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
  
  .exam-content {
    padding: 20px;
  }
  
  .target-hanzi {
    font-size: 2.5rem;
  }
  
  .exam-controls {
    flex-direction: row;
    align-items: center;
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .result-actions {
    flex-direction: column;
  }

/* 合集弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
  animation: fadeIn 0.3s ease-out;
}

.modal-content {
  background: white;
  border-radius: 15px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
  max-width: 90vw;
  max-height: 90vh;
  overflow: auto;
  animation: scaleIn 0.3s ease-out;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 1.3rem;
}

.modal-close {
  background: none;
  border: none;
  font-size: 1.8rem;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-close:hover {
  color: #333;
}

.modal-body {
  padding: 25px;
  text-align: center;
}

.collection-image {
  max-width: 100%;
  max-height: 60vh;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.modal-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 20px 25px;
  border-top: 1px solid #f0f0f0;
}

.btn-secondary {
  background: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
}

.btn-secondary:hover {
  background: #e0e0e0;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes scaleIn {
  from {
    transform: scale(0.8);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}
</style>